﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Smark.Data
{
    public class JoinTable
    {
       

        private string mTableSql = null;

      

        private FieldInfo[] mSelectFields;

        private string GetTableName(string name)
        {
            Mappings.ObjectMapper om = Mappings.ObjectMapper.GetOM(name);
            return om.Table;
        }

        public JoinTable LJoin(FieldInfo lfield, FieldInfo rfield)
        {
            if (mTableSql == null)
                mTableSql = string.Format("({0} left join {1} on {0}.{2}={1}.{3})", GetTableName(lfield.Table), GetTableName(rfield.Table),
                    lfield.Name, rfield.Name);
            else
                mTableSql = string.Format("({0} left join {3} on {1}.{2}={3}.{4})",
                    mTableSql, GetTableName(lfield.Table), lfield.Name, GetTableName(rfield.Table), rfield.Name);
              
            return this;
        }
        public JoinTable Join(FieldInfo lfield, FieldInfo rfield)
        {
            if (mTableSql == null)
                mTableSql = string.Format("({0} inner join {1} on {0}.{2}={1}.{3})", GetTableName(lfield.Table), GetTableName(rfield.Table),
                    lfield.Name, rfield.Name);
            else
                mTableSql = string.Format("({0} inner join {3} on {1}.{2}={3}.{4})",
                    mTableSql, GetTableName(lfield.Table), lfield.Name, GetTableName(rfield.Table), rfield.Name);

            return this;
        }
        public JoinTable RJoin(FieldInfo lfield, FieldInfo rfield)
        {
            if (mTableSql == null)
                mTableSql = string.Format("({0} right join {1} on {0}.{2}={1}.{3})", GetTableName(lfield.Table), GetTableName(rfield.Table),
                    lfield.Name, rfield.Name);
            else
                mTableSql = string.Format("({0} right join {3} on {1}.{2}={3}.{4})",
                    mTableSql, GetTableName(lfield.Table), lfield.Name, GetTableName(rfield.Table), rfield.Name);

            return this;
        }
        public JoinTable Select(params FieldInfo[] fields)
        {
            mSelectFields = fields;
            return this;
        }
        public void GetSql(StringBuilder sql)
        {
            if (mSelectFields != null && mSelectFields.Length > 0)
            {
                for (int i = 0; i < mSelectFields.Length; i++)
                {
                    FieldInfo field= mSelectFields[i];
                    
                    if (i > 0)
                        sql.Append(" , ");
                    sql.AppendFormat(" {0}.{1} as {2}", field.Table, field.Name, field.SuffixName == null ? field.Name : field.SuffixName);
                }
            }
            else
            {
                sql.Append("select * from " + mTableSql);
            }
        }
    }
}
